package top.lishuoboy.redis.controller;

import cn.hutool.http.HttpUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class SecondKillThreadClient {
    private static int count = 200;  // 乐观锁不乐观，冲突较多，会有遗留库存。重新抢就行
//    private static int count = 1000;

    @SneakyThrows
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(16);
        for (int userId = 0; userId < count; userId++) {
            // 制造 同一用户重复秒杀情况
            executorService.submit(new ClientThread(userId));
            executorService.submit(new ClientThread(userId));
        }
        executorService.shutdown();
    }
}

@Slf4j
@AllArgsConstructor
class ClientThread implements Runnable {
    private Integer userId;

    @Override
    public void run() {
        String context = HttpUtil.get("http://localhost:8080/skuSecondKill/" + userId);
        if (!context.startsWith("FAIL")) {  // 非 秒杀失败
            log.warn("context=={}", context);
        } else {
            log.debug("context=={}", context);
        }
    }
}